package com.web.filter;

import com.core.shared.TraceUtil;
import com.core.shared.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: xf
 * Date: 2017-12-06
 * Time: 21:42
 * To change this template use Editor | File and Code Templates.
 */
public class TraceInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(TraceInterceptor.class.getName());

    //记录请求开始处理的时间
    private ThreadLocal<Long> requestBeginTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每个请求分配一个uuid，并记录请求开始处理的时间
        String traceId = TraceUtil.assignRequestTraceId(request);
        LOGGER.info("request begin, traceid:{}, request param: {}", traceId, WebUtil.getRequestLogString(request));
        requestBeginTime.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String traceId = TraceUtil.getRequestTraceId(request);
        long requestElapseTime = System.currentTimeMillis() - requestBeginTime.get();
        if (requestElapseTime > 3 * 1000) {
            //请求大于3秒
            LOGGER.error("request end, traceid:{}, time used:{} ms", traceId, requestElapseTime);
        } else {
            LOGGER.info("request end, traceid:{}, request end,time used:{} ms", traceId, requestElapseTime);
        }
        requestBeginTime.remove();
    }

}
